#include "shader.h"
  
void read_src(const char *path, void const *buf) {
    FILE *file = fopen(path, "r");
    if (file == NULL) {
        printf("can't open file: %s\n", path);
        return;
    }
    while (!feof(file)) {
        fread((char*)buf, BUFFSIZE, 1, file);
    }
}

void compileShader(unsigned int *shader, char const *path, int flag) {
    
    // 顶点着色器
    *shader = glCreateShader(flag);
    char src[BUFFSIZE] = {0};
    read_src(path, src);
    const char* vs_src= src;
    /*
    puts("--------------------------------------------------------------\n");
    printf("%s\n", vs_src);
    puts("--------------------------------------------------------------\n");
    */
    glShaderSource(*shader, 1, &vs_src, NULL);
    glCompileShader(*shader);
    int  success;
    char infoLog[512];
    glGetShaderiv(*shader, GL_COMPILE_STATUS, &success);
    if(!success)
    {
        glGetShaderInfoLog(*shader, 512, NULL, infoLog);
        printf("ERROR::SHADER::VERTEX::COMPILATION_FAILED: %s\n%s\n", path, infoLog);
    }
}

void linkProgram(unsigned int *program, unsigned int *vs, unsigned int *fs) {
    
    *program = glCreateProgram();
    glAttachShader(*program, *vs);
    glAttachShader(*program, *fs);
    glLinkProgram(*program);
    int  success;
    char infoLog[512];
    glGetProgramiv(*program, GL_LINK_STATUS, &success);
    if(!success) {
        glGetProgramInfoLog(*program, 512, NULL, infoLog);
        printf("ERROR::SHADER::VERTEX::LINK_FAILED\n%s\n", infoLog);
    }
    glDeleteShader(*vs);
    glDeleteShader(*fs);
}
